import { Resolve } from '@angular/router';
import { Observer } from 'rxjs/Rx';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { FormGroup, FormControl, AsyncValidatorFn } from '@angular/forms';
import { Injectable, Inject } from '@angular/core';
import { PublicConfig } from "../config/config";
import 'rxjs/Rx';

@Injectable()
export class FormService {

    constructor(private http: Http, private pconfig: PublicConfig) {

    }

    // 判断密码和确认密码是否相同
    ckPassword(group: FormGroup): any {
        let password: FormControl = group.get('password') as FormControl;
        let cpwd: FormControl = group.get('cpwd') as FormControl;

        return password.value == cpwd.value ? null : { ckPassword: { errormsg: '密码和确认密码，输入不同' } }
    }

    // 验证身份证的合法性
    ckId(control: FormControl): any {
        let reg: RegExp = new RegExp('(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)');

        return reg.test(control.value) ? null : { ckId: { errormsg: '身份证验证失败' } }
    }

    // 选择区域是否都选择了
    ckArea(group: FormGroup): any {
        let area: FormControl = group.get('area') as FormControl;
        let street: FormControl = group.get('street') as FormControl;
        let community: FormControl = group.get('community') as FormControl;

        return area.value == '-1' ||
            street.value == '-1' ||
            community.value == '-1' ?
            { ckArea: { errormsg: '整个区域有没选择的' } } : null
    }

    // 验证手机号
    ckTel(control: FormControl): any {
        let reg: RegExp = new RegExp('^1[3|4|5|7|8][0-9]{9}$');
        return reg.test(control.value) ? null : { ckTel: { errormsg: '手机号验证错误' } }
    }

    // 验证是否阅读
    ckRead(control: FormControl): any {
        return control.value ? null : { ckRead: { errormsg: '请点击阅读' } }
    }

    // 验证注册用户名是否存在
    enableUserName(): AsyncValidatorFn {
        return (control: FormControl) => {
            let search: URLSearchParams = new URLSearchParams();
            search.append('userName', control.value);
            return this.http.get(this.pconfig.getApiStatus('ckUserName').url, { search: search }).debounceTime(200).map(res => {
                let result: any = null;
                
                res = res.json();

                if (res['code'] != 0) {
                    result = { enableUserName: { errormsg: res['msg'] } };
                }

                return result;
            });
        };
    }
}
